# @Time   : 2022-03-03 17:00:00
# @Author : Gavin Jiang
# @Owner  : YSRD (Insights Value)

import os
import uuid

from flask import request, g

from framework.the_path import ThePath


class ApiUtil:

    @staticmethod
    def tmp_save_req_files(allowed_mimetypes=None, clear_after_request=True):
        """
        把本次请求中上传的文件存到临时目录中
        @param allowed_mimetypes:
        允许上传的mimetype，可在api/framework/constant/mimetype.py中找到定义好的值，如果为None，则所有类型的文件都将被保存到临时目录中
        @param clear_after_request:
        是否在请求结束后自动删除临时文件，True表示删除
        @return:
        返回一个列表，列表中以dict的方式返回每个上传文件的：
        1. 原始名称（filename）
        2. 临时文件名（tmp_filename）
        3. 临时文件路径（tmp_file_path）
        4. 文件大小（size）
        """
        results = []

        if not request.files:
            return results

        file_path = ThePath.tmp('post_files')

        file_storage_list = request.files
        for key in file_storage_list.keys():
            for file_storage in file_storage_list.getlist(key):
                filename = file_storage.filename
                mimetype = file_storage.mimetype

                if allowed_mimetypes and mimetype not in allowed_mimetypes:
                    continue

                tmp_filename = str(uuid.uuid4())
                tmp_file_path = os.path.join(file_path, tmp_filename).replace('\\', '/')
                file_storage.save(tmp_file_path)

                results.append({
                    'filename': filename,
                    'tmp_filename': tmp_filename,
                    'tmp_file_path': tmp_file_path,
                    'size': os.path.getsize(tmp_file_path),
                    'clear_after_request': clear_after_request
                })

        g.upload_tmp_files = results

        return results

    @staticmethod
    def get_raw_file_storage_list(allowed_mimetypes=None):
        """
        获取本次请求中上传文件的原始FileStorage列表
        @param allowed_mimetypes: 允许上传的mimetype，可在api/framework/constant/mimetype.py中找到定义好的值
        @return: 上传文件的原始FileStorage列表
        """
        results = []
        if not request.files:
            return results

        file_storage_list = request.files
        for key in file_storage_list.keys():
            for file_storage in file_storage_list.getlist(key):
                mimetype = file_storage.mimetype

                if allowed_mimetypes and mimetype not in allowed_mimetypes:
                    continue

                results.append(file_storage)

        return results

    @staticmethod
    def keep_decimals(line, fields,number=2):
        print(line)
        for i in fields:
            line[i] = round(line[i], number)
        return line